package gui;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.border.LineBorder;

import server.Server;

public class RequestUserFrame extends JFrame {

	private Server server;
	private MainWindow mainFrame;

	private JPanel containerPanel;
	private JTextField userNameText;
	private JTextField passwordText;
	private Box buttonBox;
	private JButton okButton;
	private JButton cancelButton;
	private final Color bkg = new Color(255,99,71);

	public RequestUserFrame(MainWindow m, Server s) {
		mainFrame = m;
		server = s;
		
		setSize(300, 200);
		setTitle("Request User Access");
		containerPanel = new JPanel();
		containerPanel.setLayout(new GridLayout(0,1));
		containerPanel.setBorder(new LineBorder(bkg, 3));
		add(containerPanel);
		
		containerPanel.add(new JLabel("Enter Username:", SwingConstants.LEFT));
		userNameText = new JTextField();
		containerPanel.add(userNameText);
		containerPanel.add(new JLabel("Enter Password:"));
		passwordText = new JPasswordField();
		containerPanel.add(passwordText);
		
		buttonBox = new Box(BoxLayout.X_AXIS);
		containerPanel.add(buttonBox);
		okButton = new JButton("OK");
		okButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				final String userName = userNameText.getText();
				final String password = passwordText.getText();
				SwingWorker<String, Object> requester = new SwingWorker<String, Object>(){
					protected String doInBackground() throws Exception {
						return server.requestUserAcc(userName, password);
					}
					protected void done(){
						try {
							JOptionPane.showMessageDialog(mainFrame,
									get(), "Request Update", JOptionPane.INFORMATION_MESSAGE);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(mainFrame,
									e.getMessage() + "\n - user request error", "Error", JOptionPane.ERROR_MESSAGE);
						}
					}
				};
				requester.execute();
				JOptionPane.showMessageDialog(mainFrame,
						"Request Sent", "Request Update", JOptionPane.INFORMATION_MESSAGE);
				RequestUserFrame.this.dispose();
			}
		});
		cancelButton = new CancelButton();
		buttonBox.add(okButton);
		buttonBox.add(Box.createHorizontalStrut(20));
		buttonBox.add(cancelButton);
		
		containerPanel.setBackground(bkg);
		setVisible(true);
	}
}
